package com.java.module.user.controller.api;

import com.java.common.lang.domain.AjaxResult;
import com.java.common.lang.domain.entity.User;
import com.java.common.lang.domain.page.Page;
import com.java.common.lang.domain.page.TableDataInfo;
import com.java.common.service.ApiTokenService;
import com.java.common.utils.DateUtils;
import com.java.common.utils.WebKit;
import com.java.module.user.domain.Invite;
import com.java.module.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.java.module.user.service.IInviteService;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 用户邀请Controller
 * 
 * @author Administrator
 * @date 2025-07-08
 */
@RestController("ApiInviteController")
@RequestMapping("/user/invite")
public class InviteController {

    @Autowired
    IInviteService inviteService;


    @Autowired
    IUserService userService;

    @Autowired
    private ApiTokenService tokenService;
    @Autowired
    private ApiTokenService apiTokenService;


    @GetMapping("/list")
    public List<Invite> list(Invite invite) {
        invite.setUid(apiTokenService.getLoginUserId());
        return inviteService.selectInviteList(invite);
    }

    @PostMapping("/add")
    public AjaxResult add(@RequestBody Invite invite) {
        if (invite.getCode() == null) {
            return AjaxResult.error("当前邀请码为空");
        }
        User user = userService.selectUserByCode(invite.getCode());
        if (user == null) {
            return AjaxResult.error("当前邀请码无效");
        }
        //在判断当前邀请码是否已经被绑定
        List<Invite> invites = inviteService.selectInviteList(invite);
        if (invites.size() > 0) {
            return AjaxResult.error("当前邀请码已被绑定");
        }
        //在判断是否在自己的邀请码
        if (user.getUid() == apiTokenService.getLoginUserId()) {
            return AjaxResult.error("不可绑定自己的邀请码");
        }
        invite.setUid(tokenService.getLoginUserId());
        invite.setInvitedUid(user.getUid());
        invite.setDays(10L);
        inviteService.insertInvite(invite);
        //在这里给用户新增vip天数

        User userNews = userService.selectUserById(apiTokenService.getLoginUserId());
        //如何当前用户是vip
        if (userNews.getVip() == 1) {
            // 当前日期加10天
            if(userNews.getOverTime() == null){
                userNews.setOverTime(DateUtils.addDaysToDate(new Date(),10));
            }else{

                userNews.setOverTime(DateUtils.addDaysToDate(userNews.getOverTime(),10));
            }
            userService.updateUser(userNews);
        }else{
            //当前用户不是vip
            userNews.setVip(1);
            userNews.setOverTime(DateUtils.addDaysToDate(new Date(),10));
            userService.updateUser(userNews);
        }
        return AjaxResult.success("已绑定当前邀请码");
    }

}